import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _class, _class2;

/**
 * 数据层级配置
 */
import React, { PureComponent } from 'react';
import { Form, Modal, Spin, Table } from 'antd';
import { connect } from 'dva';
import { Bind } from 'lodash-decorators';
import Lov from "../../../components/Lov";
import formatterCollections from "../../../utils/intl/formatterCollections";
import intl from "../../../utils/intl";
import { getCurrentOrganizationId } from "../../../utils/utils";
import notification from "../../../utils/notification";
import { queryLov } from "../../../services/api";
import style from "./index.less?modules";
/**
 * 数据层级配置 Tenant
 *
 * @extends {PureComponent} - React.PureComponent
 * @reactProps {!boolean} [modalVisible=false] - 是否显示选择数据层级的模态框
 * @reactProps {!array} [expandedRowKeys=[]] - 显示的数据层级值id
 * @reactProps {!array} [renderTree=[]] - 数据层级列表数据
 * @reactProps {!array} [queryParams=[]] - 值集视图配置
 * @reactProps {!string} [dataHierarchyCode] - 数据层级编码
 * @reactProps {!string} [dataHierarchyMeaning] - 数据层级值展示值
 * @returns React.element
 */

var DefaultDataHierarchies = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_PureComponent) {
  _inherits(DefaultDataHierarchies, _PureComponent);

  var _super = _createSuper(DefaultDataHierarchies);

  /**
   * constructor - constructor方法
   * 组件构造函数
   */
  function DefaultDataHierarchies(props) {
    var _this;

    _classCallCheck(this, DefaultDataHierarchies);

    _this = _super.call(this, props);
    _this.state = {
      modalVisible: false,
      // 控制模态框显示
      expandedRowKeys: [],
      // 可展开的行数据key集合
      renderTree: [],
      // 树形列表数据源
      valueList: [],
      // 已经配置的数据层级
      queryParams: [],
      // 值集视图配置
      dataHierarchyCode: '',
      // 配置编码
      dataHierarchyMeaning: '',
      // 配置显示值
      dataHierarchyId: ''
    };
    return _this;
  }
  /**
   * @function renderTreeData - 渲染树
   * @param {!array} collections - 查询获取的数据
   */


  _createClass(DefaultDataHierarchies, [{
    key: "renderTreeData",
    value: function renderTreeData() {
      var _this2 = this;

      var collections = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var levelPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
      var query = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
      var pathMap = levelPath;
      var valueList = value;
      var queryParams = query;
      var renderTree = collections.map(function (item) {
        var temp = item;
        pathMap[temp.dataHierarchyId] = [].concat(_toConsumableArray(pathMap[temp.parentId] || []), [temp.dataHierarchyId]);
        valueList.push(temp.dataHierarchyValue && temp.dataHierarchyId);
        queryLov({
          viewCode: temp.valueSourceCode
        }).then(function (res) {
          var valueField = res.valueField,
              displayField = res.displayField;
          queryParams.push(_defineProperty({}, temp.dataHierarchyId, {
            valueField: valueField,
            displayField: displayField
          }));
        });

        if (temp.children) {
          temp.children = _toConsumableArray(_this2.renderTreeData(temp.children || [], pathMap, valueList, queryParams).renderTree);
        }

        return temp;
      });
      this.setState({
        valueList: valueList,
        queryParams: queryParams
      });
      return {
        renderTree: renderTree,
        pathMap: pathMap,
        valueList: valueList,
        queryParams: queryParams
      };
    }
    /**
     * @function renderTreeData - 遍历获取父节点
     * @param {!array} record - 当前的数据
     */

  }, {
    key: "handleFind",
    value: function handleFind() {
      var _this3 = this;

      var record = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var renderTree = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var dataHierarchyValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
      var dataHierarchyId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
      var parentId = record.parentId;
      var value = dataHierarchyValue;
      var id = dataHierarchyId;
      var traverse = renderTree.map(function (item) {
        var temp = item;

        if (temp.dataHierarchyId === parentId) {
          value = temp.dataHierarchyValue;
          id = temp.dataHierarchyId;
        }

        if (temp.children) {
          temp.children = _toConsumableArray(_this3.handleFind({
            parentId: parentId
          }, temp.children || [], value, id).traverse);
        }

        return temp;
      });
      return {
        parentId: parentId,
        traverse: traverse,
        value: value,
        id: id
      };
    }
    /**
     * @function handleOpenModal - 显示和隐藏租户切换模态框
     * @param {boolean} flag - 显示或隐藏标识
     */

  }, {
    key: "handleOpenModal",
    value: function handleOpenModal(flag) {
      var _this4 = this;

      var dispatch = this.props.dispatch;

      if (flag) {
        dispatch({
          type: 'user/fetchDataHierarchiesList',
          payload: {
            organizationId: getCurrentOrganizationId()
          }
        }).then(function (res) {
          if (res) {
            var _this4$renderTreeData = _this4.renderTreeData(res),
                renderTree = _this4$renderTreeData.renderTree,
                _this4$renderTreeData2 = _this4$renderTreeData.pathMap,
                pathMap = _this4$renderTreeData2 === void 0 ? {} : _this4$renderTreeData2;

            var expandedRowKeys = Object.keys(pathMap).map(function (item) {
              return +item;
            });

            _this4.setState({
              renderTree: renderTree,
              expandedRowKeys: expandedRowKeys
            });
          }
        });
      } else {
        // 清缓存
        this.setState({
          expandedRowKeys: [],
          renderTree: [],
          valueList: [],
          dataHierarchyCode: '',
          dataHierarchyMeaning: '',
          dataHierarchyId: ''
        });
      }

      this.setState({
        modalVisible: flag
      });
    }
    /**
     * @function handleClear - 清除层级编码
     */

  }, {
    key: "handleClear",
    value: function handleClear(params) {
      var _params$dataHierarchy = params.dataHierarchyCode,
          dataHierarchyCode = _params$dataHierarchy === void 0 ? '' : _params$dataHierarchy,
          _params$dataHierarchy2 = params.dataHierarchyId,
          dataHierarchyId = _params$dataHierarchy2 === void 0 ? '' : _params$dataHierarchy2;
      this.setState({
        dataHierarchyCode: dataHierarchyCode,
        dataHierarchyId: dataHierarchyId
      });
    }
    /**
     * @function handleSet - 设置层级编码
     */

  }, {
    key: "handleSet",
    value: function handleSet(params) {
      var _this5 = this;

      var _params$dataHierarchy3 = params.dataHierarchyCode,
          dataHierarchyCode = _params$dataHierarchy3 === void 0 ? '' : _params$dataHierarchy3,
          dataHierarchyId = params.dataHierarchyId;
      var queryParams = this.state.queryParams;
      queryParams.map(function (item) {
        if (item[dataHierarchyId]) {
          _this5.setState({
            dataHierarchyCode: dataHierarchyCode,
            dataHierarchyId: dataHierarchyId,
            dataHierarchyMeaning: item[dataHierarchyId].displayField
          });
        }

        return 0;
      });
    }
    /**
     * @function handleChange - 切换层级配置
     */

  }, {
    key: "handleChange",
    value: function handleChange(_, params) {
      var _this6 = this;

      var dataHierarchyMeaning = this.state.dataHierarchyMeaning;
      var meaning = dataHierarchyMeaning;
      this.setState({
        dataHierarchyMeaning: params[meaning]
      }, function () {
        return _this6.handleSwitch();
      });
    }
    /**
     * @function handleSwitch - 切换层级配置请求
     */

  }, {
    key: "handleSwitch",
    value: function handleSwitch() {
      var _this7 = this;

      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          form = _this$props.form;
      var _this$state = this.state,
          dataHierarchyMeaning = _this$state.dataHierarchyMeaning,
          dataHierarchyCode = _this$state.dataHierarchyCode,
          dataHierarchyId = _this$state.dataHierarchyId;
      var fieldValues = form.getFieldValue("dataHierarchyValue".concat(dataHierarchyId));
      dispatch({
        type: 'user/switchDataHierarchies',
        payload: {
          dataHierarchyMeaning: dataHierarchyMeaning,
          dataHierarchyCode: dataHierarchyCode,
          dataHierarchyValue: fieldValues,
          organizationId: getCurrentOrganizationId()
        }
      }).then(function (res) {
        if (res) {
          form.resetFields();
          notification.success();

          _this7.handleOpenModal(true);
        }
      });
    }
    /**
     * 点击'+',获取当前节点的下级节点
     * @param {Boolean} isExpand 展开标记
     * @param {Object} record  当前行
     */

  }, {
    key: "handleExpandRow",
    value: function handleExpandRow(isExpand, record) {
      var expandedRowKeys = this.state.expandedRowKeys;
      var rowKeys = isExpand ? [].concat(_toConsumableArray(expandedRowKeys), [record.dataHierarchyId]) : expandedRowKeys.filter(function (item) {
        return item !== record.dataHierarchyId;
      });
      this.setState({
        expandedRowKeys: _toConsumableArray(rowKeys)
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this8 = this;

      var fetchLoading = this.props.fetchLoading;
      var _this$state2 = this.state,
          expandedRowKeys = _this$state2.expandedRowKeys,
          renderTree = _this$state2.renderTree,
          _queryParams = _this$state2.queryParams;
      var columns = [{
        title: intl.get('cpaas.common.components.dataHierarchies.dataHierarchyName').d('数据层级名称'),
        width: 100,
        dataIndex: 'dataHierarchyName'
      }, {
        title: intl.get('cpaas.common.components.dataHierarchies.dataHierarchyVal').d('数据层级值'),
        width: 100,
        render: function render(_, record) {
          var form = _this8.props.form;
          var valueList = _this8.state.valueList;
          var valueSourceCode = record.valueSourceCode,
              dataHierarchyMeaning = record.dataHierarchyMeaning,
              dataHierarchyValue = record.dataHierarchyValue,
              dataHierarchyId = record.dataHierarchyId;
          return /*#__PURE__*/React.createElement(Form.Item, {
            className: style['data-hierarchies-td']
          }, form.getFieldDecorator("dataHierarchyValue".concat(dataHierarchyId), {
            initialValue: dataHierarchyValue
          })( /*#__PURE__*/React.createElement(Lov, {
            code: valueSourceCode,
            textValue: dataHierarchyMeaning,
            allowClear: true,
            disabled: record.parentId ? !valueList.some(function (item) {
              return item === record.parentId;
            }) : false,
            onClear: function onClear() {
              return _this8.handleClear(record);
            },
            onClick: function onClick() {
              return _this8.handleSet(record, renderTree);
            },
            onChange: _this8.handleChange,
            queryParams: function queryParams() {
              if (record.parentId) {
                var _ref;

                var _this8$handleFind = _this8.handleFind(record, renderTree),
                    value = _this8$handleFind.value,
                    id = _this8$handleFind.id;

                var code = '';

                _queryParams.map(function (item) {
                  if (item[id]) {
                    code = item[id].valueField;
                  }

                  return 0;
                });

                return code ? (_ref = {}, _defineProperty(_ref, code, value), _defineProperty(_ref, "tenantId", getCurrentOrganizationId()), _ref) : {
                  tenantId: getCurrentOrganizationId()
                };
              } else {
                return {
                  tenantId: getCurrentOrganizationId()
                };
              }
            }
          })));
        }
      }];
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
        style: {
          color: '#666'
        },
        size: "small",
        onClick: function onClick() {
          return _this8.handleOpenModal(true);
        }
      }, intl.get('cpaas.common.view.message.title.list').d('数据层级配置')))), /*#__PURE__*/React.createElement(Modal, {
        title: intl.get('cpaas.common.view.message.title.list').d('数据层级配置'),
        width: "620px",
        bodyStyle: {
          paddingTop: 0,
          height: '460px'
        },
        visible: this.state.modalVisible,
        onCancel: function onCancel() {
          return _this8.handleOpenModal(false);
        },
        footer: null
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: false
      }, /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        className: style['data-hierarchies'],
        rowKey: "dataHierarchyId",
        pagination: false,
        dataSource: renderTree,
        columns: columns,
        scroll: {
          y: 360
        },
        expandedRowKeys: expandedRowKeys,
        loading: fetchLoading,
        onExpand: this.handleExpandRow
      }))));
    }
  }]);

  return DefaultDataHierarchies;
}(PureComponent), (_applyDecoratedDescriptor(_class2.prototype, "renderTreeData", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "renderTreeData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleFind", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "handleFind"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleOpenModal", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleOpenModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleClear", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleClear"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSet", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSet"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleChange", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "handleChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSwitch", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSwitch"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleExpandRow", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "handleExpandRow"), _class2.prototype)), _class2)) || _class);
export default formatterCollections({
  code: 'cpfm.tenantSelect'
})(connect(function (_ref2) {
  var _ref2$user = _ref2.user;
  _ref2$user = _ref2$user === void 0 ? {} : _ref2$user;
  var _ref2$user$hierarchic = _ref2$user.hierarchicalList,
      hierarchicalList = _ref2$user$hierarchic === void 0 ? [] : _ref2$user$hierarchic,
      loading = _ref2.loading;
  return {
    hierarchicalList: hierarchicalList,
    fetchLoading: loading.effects['user/fetchDataHierarchiesList'] || loading.effects['user/switchDataHierarchies']
  };
})(DefaultDataHierarchies));